package com.peng.leetcode.tree;

/**
 * PathSum1
 *
 * 面试题 04.12. 求和路径
 *
 * @author: lupeng6
 * @create: 2021/2/23 14:28
 */
public class PathSum1 {

    public static void main(String[] args) {
        TreeNode node = TreeMain.array2tree(new Integer[]{5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1});
        int sum = 22;
        System.out.println(new PathSum1().pathSum(node, sum));
    }


    private int answer;
    private int sum;

    public int pathSum(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        this.sum = sum;
        dfs(root);
        return answer;
    }

    private void dfs(TreeNode node) {
        if (node == null) {
            return;
        }
        dfsSum(node, 0);

        dfs(node.left);
        dfs(node.right);
    }

    private void dfsSum(TreeNode node, int currentSum) {
        if (node == null) {
            return;
        }
        currentSum += node.val;
        if (currentSum == sum) {
            answer++;
        }
        dfsSum(node.left, currentSum);
        dfsSum(node.right, currentSum);
    }
}
